package com.example.webdriveddd.factory;

import com.example.webdriveddd.application.AppException;
import com.example.webdriveddd.application.IllegalArgException;
import com.example.webdriveddd.application.NotFoundException;
import com.example.webdriveddd.domain.FileInfo;
import com.example.webdriveddd.domain.User;
import com.example.webdriveddd.dto.FileInfoDTO;
import com.example.webdriveddd.repository.FileRepository;
import com.example.webdriveddd.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class FileInfoFactory {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private FileRepository fileRepository;
    public FileInfo fromDTO(FileInfoDTO fileInfoDTO) throws AppException {
        User user=userRepository.findById(fileInfoDTO.getUserId()).orElseThrow(()->{
            return new NotFoundException("user with id "+fileInfoDTO.getUserId()+" not found",null);
        });
        FileInfo parentFile=null;
        if (fileInfoDTO.getParentId()>0){
            parentFile=fileRepository.findById(fileInfoDTO.getParentId()).orElseThrow(()->{
                return new NotFoundException("file with id "+fileInfoDTO.getParentId()+" not found",null);
            });
            if (parentFile.isFile()){
                throw new IllegalArgException("parent file must be a dir",null);
            }
        }
        FileInfo fileInfo=new FileInfo(fileInfoDTO.getFileName(), fileInfoDTO.getFileType(), fileInfoDTO.getFileSize(),parentFile,user);
        fileInfo.setDescription(fileInfo.getDescription());
        return fileInfo;
    }
    public FileInfo rootFile(int userId) throws NotFoundException {
        User user=userRepository.findById(userId).orElseThrow(()->{
            return new NotFoundException("user with id "+userId+" not found",null);
        });
        return new FileInfo("/","dir",0,null,user);
    }
}
